package ar.unc.famaf.pln.giveselector.selectors;

import java.io.*;
import java.util.*;
import java.util.zip.GZIPInputStream;

import ar.unc.famaf.pln.giveselector.context.Utterance;


/**
 * A DefaultSelector is an abstract UtteranceSelector that takes care for loading the corpus. 
 * Child classes must implement selectUtterance and selectUtterances.
 * @author Alexandre Denis
 */
public abstract class DefaultSelector implements ISelector
{
	// <world name, utterances>
	protected Map<String, Set<Utterance>> utterances = new HashMap<String, Set<Utterance>>();


	/**
	 * Creates an DefaultSelector with a default RandomSelector.
	 */
	public DefaultSelector(File corpus)
	{
		load(corpus);
	}


	/**
	 * Creates a DefaultSelector.
	 */
	public DefaultSelector(Map<String, Set<Utterance>> utterances)
	{
		this.utterances = utterances;
	}

	
	/**
	 * Retrieves the loaded Utterances Map
	 */
	public Map<String, Set<Utterance>> getUtterances()
	{
		return utterances;
	}


	/**
	 * Loads this DefaultComparisonSelector to given file.
	 */
	@SuppressWarnings("unchecked")
	public void load(File fileName)
	{
		FileInputStream fis = null;
		GZIPInputStream gis = null;
		ObjectInputStream in = null;
		try
		{
			fis = new FileInputStream(fileName);
			gis = new GZIPInputStream(fis);
			in = new ObjectInputStream(gis);
			utterances = (Map<String, Set<Utterance>>) in.readObject();
			in.close();
		}
		catch (InvalidClassException ex)
		{
			System.err.println("Exception: " + ex.getMessage());
			System.err.println("Unable to read " + fileName + " : probably the Utterance class has changed since");
			System.err.println("Try to regenerate the file with UtteranceBuilder");
			System.exit(-1);
		}
		catch (IOException ex)
		{

			ex.printStackTrace();
		}
		catch (ClassNotFoundException ex)
		{
			ex.printStackTrace();
		}
	}
}
